﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Network
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            /* 获取电脑上可用的串口号 */
            string[] ports = System.IO.Ports.SerialPort.GetPortNames();
            /* 把可用串口号添加到界面 */
            comboBox_Port.Items.AddRange(ports);
            comboBox_Port.SelectedIndex = comboBox_Port.Items.Count > 0 ? 0 : -1;

            comboBox_baud.Text = "115200";

            textBox_path.Text = "/";
            comboBox_path_type.Text = "0 (文件)";
            textBox_offset.Text = "0";
            textBox_size.Text = "0";
            textBox_data_length.Text = "200";
        }

        private void button_open_Click(object sender, EventArgs e)
        {
            if (button_open.Text == "打开")
            {
                try
                {
                    RS485.PortName = comboBox_Port.Text;
                    RS485.BaudRate = int.Parse(comboBox_baud.Text);
                    RS485.DataBits = 8;
                    RS485.StopBits = System.IO.Ports.StopBits.One;
                    RS485.Parity = System.IO.Ports.Parity.None;

                    RS485.Open();
                    button_open.Text = "关闭";
                }
                catch (Exception err)
                {
                    MessageBox.Show("串口打开失败" + err.ToString());
                }
            }
            else
            {
                try
                {
                    RS485.Close();
                    button_open.Text = "打开";
                }
                catch (Exception err)
                {
                    MessageBox.Show("串口关闭失败" + err.ToString());
                }
            }
        }

        private void button_data_clear_Click(object sender, EventArgs e)
        {
            textBox_data_read.Clear();
        }

        private void RS485_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            int length = RS485.BytesToRead;
            byte[] readBuff = new byte[length];
            RS485.Read(readBuff, 0, length);
            string readStrings = Encoding.Default.GetString(readBuff);
            Invoke((new Action(() => //C# 3.0以后代替委托的新方法
            {
                if (checkBox_hex.Checked)
                {
                    textBox_data_read.AppendText(readStrings);
                }
                else
                {
                    textBox_data_read.AppendText(readStrings);
                }
            })));
        }
    }
}
